package dev.hax.commandwatch

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        loadReference()
        requestOverlay()
        setupUI()
        setupCommands()
    }

    private var id: String? = null
    private var server: String? = null
    private var port: String? = null

    private fun loadReference() {
        val sharedPreferences = getSharedPreferences("watch", Context.MODE_PRIVATE)
        id = sharedPreferences.getString("id", "pad")
        server = sharedPreferences.getString("server", "192.168.1.3")
        port = sharedPreferences.getString("port", "31023")
    }

    private fun saveReference() {
        val sharedPreferences = getSharedPreferences("watch", Context.MODE_PRIVATE)
        sharedPreferences.edit()
            .putString("id", id)
            .putString("server", server)
            .putString("port", port)
            .apply()
    }

    private fun requestOverlay() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //若未授权则请求权限
            if (!Settings.canDrawOverlays(this)) {
                AlertDialog.Builder(this)
                    .setMessage("需要浮窗权限以在后台启动其他应用")
                    .setNegativeButton("拒绝") { _, _ -> }
                    .setPositiveButton("允许") { _, _ ->
                        val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                        intent.data = Uri.parse("package:$packageName")
                        startActivityForResult(intent, 1486)
                    }
                    .show()
            }
        }
    }

    private fun setupUI() {
        idEdit.setText(id)
        serverEdit.setText(server)
        portEdit.setText(port)

        start.setOnClickListener {
            id = idEdit.text.toString()
            server = serverEdit.text.toString()
            port = portEdit.text.toString()
            saveReference()

            val intent = Intent(this, WatchService::class.java)
            intent.putExtra("id", id)
            intent.putExtra("server", server)
            intent.putExtra("port", port)
            startService(intent)
            moveTaskToBack(false)
        }
        stop.setOnClickListener {
            val intent = Intent(this, WatchService::class.java)
            stopService(intent)
        }
    }

    private fun setupCommands() {
        command1.setOnClickListener {
            sendCommand(commandKey1.text.toString(), commandContent1.text.toString())
        }
        command2.setOnClickListener {
            sendCommand(commandKey2.text.toString(), commandContent2.text.toString())
        }
        command3.setOnClickListener {
            sendCommand(commandKey3.text.toString(), commandContent3.text.toString())
        }
        command4.setOnClickListener {
            sendCommand(commandKey4.text.toString(), commandContent4.text.toString())
        }
        command5.setOnClickListener {
            sendCommand(commandKey5.text.toString(), commandContent5.text.toString())
        }
        command6.setOnClickListener {
            sendCommand(commandKey6.text.toString(), commandContent6.text.toString())
        }
        command7.setOnClickListener {
            sendCommand(commandKey7.text.toString(), commandContent7.text.toString())
        }
    }

    private fun sendCommand(key: String, content: String) {
        Thread {
            val command = JSONObject().apply {
                put("key", key)
                put("open", content)
            }

            val httpUrl = "http://$server:$port/api/order/set".toHttpUrl()
            val request = Request.Builder()
                .post(
                    command.toString()
                        .toRequestBody("application/json; charset=utf-8".toMediaType())
                )
                .url(httpUrl)
                .build()

            try {
                val client = OkHttpClient()
                client.newCall(request).execute()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }.start()
    }
}